package cn.cyber.wxfire.service;

import cn.cyber.wxfire.entity.BaseButton;
import cn.cyber.wxfire.entity.Button;
import cn.cyber.wxfire.entity.MenuButton;
import cn.cyber.wxfire.entity.ViewButton;
import cn.cyber.wxfire.http.WXHttpResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author gjn
 * @since 2021/9/18 12:54
 */
@Service
@Slf4j
public class MenuService {

    @Resource
    private WXService wxService;
    @Resource
    private AccessTokenService tokenService;

    public boolean hasMenu() {
        boolean flag = true;
        Map<String, Object> menu = wxService.getMenuFromServer(tokenService.getAccessTokenStr());
        if ( 0 == Integer.parseInt(String.valueOf(menu.get("is_menu_open"))) ) {
            log.error("is_menu_open的值0，自定义菜单未开启，请联系管理员开启自定义菜单！");
            flag = false;
        }else if (menu.get("selfmenu_info") == null) {
            log.error("is_menu_open的值为null，未获取到菜单信息，菜单为空。");
            flag = false;
        }
        return  flag;
    }

    /**
     * 设置菜单
     * @return
     */
    public WXHttpResult setMenu() {
        List<BaseButton> buttons = new ArrayList<>();

        //
//        List<BaseButton> subButtons1 = new ArrayList<>();

        ViewButton menuButton1 = new ViewButton("学院数据","http://4g67ht.natappfree.cc/classData.html");
        buttons.add(menuButton1);

        // 第二个一级菜单


        ViewButton menuButton2 = new ViewButton("我的", "http://4g67ht.natappfree.cc/");
        buttons.add(menuButton2);

        // 第三个一级菜单
        List<BaseButton> subButtons3 = new ArrayList<>();
        subButtons3.add(new ViewButton("常用下载", "https://www.qfnu.edu.cn/"));
        subButtons3.add(new ViewButton("最新政策", "https://www.qfnu.edu.cn/"));
        subButtons3.add(new ViewButton("关于我们", "http://zhjw.qfnu.edu.cn"));
        MenuButton menuButton3 = new MenuButton("更多服务", subButtons3);
        buttons.add(menuButton3);

        Button button = new Button(buttons);

        ObjectMapper mapper = new ObjectMapper();
        String menuStr = null;
        try {
            menuStr = mapper.writeValueAsString(button);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return wxService.setMenuFromServer(tokenService.getAccessTokenStr(), menuStr);
    }

    public WXHttpResult delMenu() {
        return wxService.delMenuFromServer(tokenService.getAccessTokenStr());
    }
}
